package net.lesscoding.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.Const;
import org.junit.Test;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * @author eleven
 * @date 2024/10/23 15:03
 * @apiNote
 */
@Slf4j
public class ClientTest {

    /**
     * 使用sync() 方法阻塞等待连接建立， 然后获取channel
     *
     * @throws InterruptedException
     */
    @Test
    public void simpleClientTest() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        // 1. 启动器，负责组装netty组件，启动服务
        Channel channel = new Bootstrap()
                // 2. 添加事件循环组   BossEventLoop, WorkerEventLoop(selector, thread)
                .group(new NioEventLoopGroup())
                // 3. 选择服务器的ServerSocketChannel的实现类
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 5. 在连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new StringEncoder());
                    }
                })
                // 6. 连接服务器
                .connect(new InetSocketAddress(Const.HOST, Const.PORT))
                // 7. 阻塞等待连接建立
                .sync()
                // 8. 获取channel
                .channel();
        System.out.println(channel);
        // 9. 向服务器发送数据
        channel.writeAndFlush("hello, chat!看看支不支持中文啊");
        latch.await();
    }

    /**
     * 使用监听器， 异步非阻塞， 连接建立后执行回调方法
     */
    @Test
    public void listenerTest() throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                // 2. 添加事件循环组   BossEventLoop, WorkerEventLoop(selector, thread)
                .group(new NioEventLoopGroup())
                // 3. 选择服务器的ServerSocketChannel的实现类
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 5. 在连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addLast(new StringEncoder());
                    }
                })
                // 6. 连接服务器
                /**
                 * 异步非阻塞， main发起调用， 真正执行 connect 的是 nio 线程
                 * 连接后返回 ChannelFuture，
                 * 可以使用 sync() 阻塞线程获取channel
                 * 或者添加监听器， 连接建立后执行回调方法
                 */
                .connect(new InetSocketAddress(Const.HOST, Const.PORT));
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                channel.writeAndFlush("hello, chat!看看支不支持中文啊");
                log.info("发送成功");
            }
        });
        channelFuture.addListener((ChannelFutureListener) future -> {
            Channel channel = future.channel();
            channel.writeAndFlush("hello, chat!看看支不支持中文啊");
            log.info("发送成功");
        });
        new CountDownLatch(1).await();
    }

    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(Const.HOST, Const.PORT));
        Channel channel = channelFuture.sync().channel();
        log.debug("channel: {}", channel);
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();
                if ("q".equals(line)) {
                    channel.close();
                    log.debug("channel closed");
                    break;
                }
                channel.writeAndFlush(line);
            }
            ;
        }, "SystemInput").start();
    }

    @Test
    public void closeFutureTest() throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress(Const.HOST, Const.PORT));
        Channel channel = channelFuture.sync().channel();
        ChannelFuture closeFuture = channel.closeFuture();
        //log.info("waiting close....");
        //closeFuture.sync();
        //log.info("后续处理");
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.info("关闭后续处理");
                group.shutdownGracefully();
            }
        });
    }
}
